package com.yvan;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

/**
 * Created by zzy on 2018/3/31.
 */
public class GsonUtils {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.writerWithDefaultPrettyPrinter();

/*        objectYamlMapper = new ObjectMapper(new YAMLFactory());
        objectYamlMapper.writerWithDefaultPrettyPrinter();*/
    }

    public static <T> String Object2Json(T obejct) {
        Gson gson = new Gson();
        String json = gson.toJson(obejct);
        return json;
    }

    public static <T> T Json2Object(String json, Class<T> type) {
        Gson gson = new Gson();
        T result = gson.fromJson(json, type);
        return result;
    }

    /**
     * 将Json字符串序列化成指定对象
     */
    public static <T> T jsonToObj(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
